//
//  ViewController.swift
//  剂查查
//
//  Created by shoubin tao on 2024/11/30.
//  Copyright © 2024 shipin. All rights reserved.
//

import UIKit
import CommonTools
import TYUIKit
import HandyJSON

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var loginBg: UIView!
    
    @IBOutlet weak var bgView: UIView!
    
    @IBOutlet weak var phoneTextField: UITextField!
    
    @IBOutlet weak var passwordTextField: UITextField!
    
    @IBOutlet weak var wxBottomSpace: NSLayoutConstraint!
    
    @IBOutlet weak var appleLoginCenterX: NSLayoutConstraint!
    
    @IBOutlet weak var appleLoginBtn: UIButton!
    
    @IBOutlet weak var wxLoginBtn: UIButton!
    
    
    
    
    func addGradientBackground(to view: UIView) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(x: 0, y: 0, width: 323, height: 55)
//        gradientLayer.colors = [UIColor.init(red: 0/255.0, green: 217/255.0, blue: 202/255.0, alpha: 1), UIColor.init(red: 80/255.0, green: 137/255.0, blue: 250/255.0, alpha: 1)] // 渐 渐变色设置为红色到蓝色
        gradientLayer.endPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.startPoint = CGPoint(x: 1, y: 0.5)
        gradientLayer.colors = [UIColor.init(hex:"#5089FA").cgColor, UIColor.init(hex:"#00D9CA").cgColor] // 渐变色设置为红色到蓝色
        view.layer.insertSublayer(gradientLayer, at: 0)
    }
    
    override func viewWillAppear(_ animated: Bool) {
//        if (JCCTools.token() != "")
//        {
//            if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "JCCScanTipViewController") {
//                    self.navigationController?.pushViewController(viewController, animated: false)
//            }
//        }
//        self.navigationController?.navigationBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.bgView.clipsToBounds = true
        self.bgView.layer.cornerRadius = 30
        
        self.loginBg.clipsToBounds = true
        self.loginBg.layer.cornerRadius = 30
        addGradientBackground(to: self.loginBg)
        
        self.phoneTextField.delegate = self
        self.passwordTextField.delegate = self
        let impl = XWWeChatOpenSDKBridgeProtocolImpl.shared
        if !impl.isWXAppInstalled {
            appleLoginCenterX.constant = 0
            wxLoginBtn.isHidden = true
        }
//        appleLoginBtn.cut(withRadius: 26)
        appleLoginBtn.setTitle("", for: .normal)

        if TY_ScreenSafeBottom() == 0 {
            wxBottomSpace.constant = 10
            
        }
        view.adaptScreen()
        
        
//        //使用方法
//        self.codeView = [[WMZCodeView sharedInstance] addCodeViewWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, 50)  withBlock:^(BOOL success) {
//            if (success) {
//                NSLog(@"成功");
//            }
//        }];
//        
//       [self.view addSubview:self.codeView];
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            // 将text field的内容添加到你的数据模型或者用途中
            // ...
     
            // 使用这个方法来退出键盘
            textField.resignFirstResponder()
            return true
        }
    
    @IBAction func loginAction(_ sender: Any) {
        EZLoadingActivity.show("正在登录...", disableUI: true)
        JCCNet.login(phone: self.phoneTextField.text ?? "" , password: self.passwordTextField.text ?? "", completion: {model,error  in
            if (model?.isSuccess == true) {
                EZLoadingActivity.hide()
                let dict = model?.result as! [String:Any]
                let token:String = dict["token"] as! String
                UserDefaults.standard.set("Bearer \(token )", forKey: "token")
                pushToSBVC(name: "JCCScanTipViewController")
                JCCUser.loadUserInfo()
            }else {
                EZLoadingActivity.Settings.SuccessText = model?.info ?? ""
                EZLoadingActivity.hide(true, animated: false)
            }
        })
//        pushToSBVC(name: "JCCScanTipViewController")
    }
    
    @IBAction func wxLogin(_ sender: UIButton) {
        let impl = XWWeChatOpenSDKBridgeProtocolImpl.shared
        impl.sendAuthReq(viewController: self) { code in
            NetworkRequest<Any>.request(networkType: .getWxAccessToken(code: code)) { result in
                switch result {
                case .success(let response):
                    
                    guard let response = response as? [String: Any], let access_token = response["access_token"] as? String, let openid = response["openid"] as? String else {return}
                    XWLog(value: "获取access_token成功：\(response)")
                    NetworkRequest<ThirdLoginModel>.request(networkType: .wxLogin(access_token: access_token, openid: openid)) { result in
                        switch result {
                        case .success(let response):
                            guard let response = response else {return}
                            XWLog(value: "微信登录成功：\(response)")
                            self.gotoBind(model: response)
                        case .failure(let error):
                            XWLog(value: "微信登录失败")
                        }
                    }
                case .failure(let error):
                    XWLog(value: "获取access_token失败")
                }
            }
            
        }
    }
    
    @IBAction func pravicy(_ sender: UIButton) {
        
        showPrivacy(type: sender.tag == 0 ? .privacy : .user)
    }
    
    @IBAction func appleLogin(_ sender: UIButton) {
        AppleLoginManager.share.loginAppleId { identityToken, authorizationCode, user, nickName in
            NetworkRequest<ThirdLoginModel>.request(networkType: .appleLogin(user: user, nickname: nickName)) { result in
                switch result {
                case .success(let response):
                    guard let response = response else {return}
                    XWLog(value: "苹果登录成功:\(response)" )
                    self.gotoBind(model: response)
                case .failure(let error):
                    XWLog(value: "苹果登录失败:\(error)")
                }
            }
        } failureHandle: { errorType in
            XWLog(value: "errorType:\(errorType)")
        }

    }
    
    
    
    @IBAction func forgetPwd(_ sender: UIButton) {
        
        let vc = JCCForgetPasswordViewController()
        show(vc, sender: nil)
    }
    
    func gotoBind(model: ThirdLoginModel) {
//        UserDefaults.standard.set("Bearer \(model.token )", forKey: "token")
        if model.bind_phone == 0 {
            let vc = JCCBindPhoneViewController()
            vc.token = "Bearer \(model.token )"
            show(vc, sender: nil)
        }
        else {
            pushToSBVC(name: "JCCScanTipViewController")
            JCCUser.loadUserInfo()
        }
    }
}

struct ThirdLoginModel: HandyJSON {
    init() {}
    let bind_phone: Int = 0
    let token: String = ""
}
